<template>
  <view class="tictactoe-game-container">
    <!-- 头部信息 -->
    <view class="game-header">
      <view class="header-title">井字棋</view>
      <view class="user-info">{{ userName }}</view>
      <view class="game-status">{{ currentPlayer === userId ? '你的回合' : '对方回合' }}</view>
      <view class="game-tip">{{ gameTip }}</view>
    </view>

    <!-- 游戏区域 -->
    <view class="game-area">
      <h2 class="game-title"><i class="fa fa-th-large"></i> 井字棋对战</h2>

      <!-- 玩家列表 -->
      <view class="player-list">
        <view class="player-card" :class="{ 'current': currentPlayer === players[0]?.user_id }">{{ players[0]?.user_name || '等待加入...' }}
          <view class="piece-type"><i class="fa fa-times"></i></view>
        </view>
        <view class="player-card" :class="{ 'current': currentPlayer === players[1]?.user_id }">{{ players[1]?.user_name || '等待加入...' }}
          <view class="piece-type"><i class="fa fa-circle-o"></i></view>
        </view>
      </view>

      <!-- 游戏棋盘 -->
      <view class="game-board">
        <view class="board-row" v-for="(row, i) in gameState.board" :key="i">
          <view class="board-cell" v-for="(cell, j) in row" :key="j" @tap="handleCellTap(i, j)">
            <view class="cell-content" :class="cell">
              <i class="fa fa-times" v-if="cell === 'X'"></i>
              <i class="fa fa-circle-o" v-if="cell === 'O'"></i>
            </view>
          </view>
        </view>
      </view>

      <!-- 控制按钮 -->
      <view class="control-buttons">
        <button @tap="restartGame" class="restart-btn">重新开始</button>
        <button @tap="toggleReadyStatus" class="ready-btn">{{ isReady ? '取消准备' : '准备' }}</button>
        <button @tap="backToLobby" class="back-btn">返回大厅</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';

// 路由实例
const router = useRouter();

// 游戏状态
const gameState = reactive({
  board: [],
  rows: 3,
  cols: 3,
  winner: null,
  gameOver: false,
  tie: false
});

// 响应式变量
const userId = ref('');
const userName = ref('');
const roomId = ref('');
const players = ref([]);
const isReady = ref(false);
const currentPlayer = ref('');
const gameTip = ref('等待玩家加入...');

/**
 * 初始化棋盘
 */
function initBoard() {
  gameState.board = [];
  gameState.winner = null;
  gameState.gameOver = false;
  gameState.tie = false;
  currentPlayer.value = players.value[0]?.user_id || '';
  gameTip.value = currentPlayer.value === userId.value ? '你的回合' : '对方回合';

  // 创建空棋盘
  for (let i = 0; i < gameState.rows; i++) {
    gameState.board[i] = [];
    for (let j = 0; j < gameState.cols; j++) {
      gameState.board[i][j] = null; // null: 空, 'X': X棋, 'O': O棋
    }
  }
}

/**
 * 处理棋盘格子点击
 */
function handleCellTap(i, j) {
  if (gameState.gameOver || currentPlayer.value !== userId.value || !isReady.value || gameState.board[i][j] !== null) {
    return;
  }

  // 落子
  const pieceType = currentPlayer.value === players.value[0]?.user_id ? 'X' : 'O';
  gameState.board[i][j] = pieceType;

  // 检查是否获胜
  if (checkWin(i, j, pieceType)) {
    gameState.winner = currentPlayer.value;
    gameState.gameOver = true;
    gameTip.value = `${players.value.find(p => p.user_id === currentPlayer.value)?.user_name} 获胜！`;
  } else if (checkTie()) {
    gameState.tie = true;
    gameState.gameOver = true;
    gameTip.value = '平局！';
  } else {
    // 切换玩家
    currentPlayer.value = currentPlayer.value === players.value[0]?.user_id ? players.value[1]?.user_id : players.value[0]?.user_id;
    gameTip.value = currentPlayer.value === userId.value ? '你的回合' : '对方回合';
  }

  // 发送落子信息到服务器 (实际应用中需要实现)
  // sendMove(i, j, pieceType);
}

/**
 * 检查是否获胜
 */
function checkWin(i, j, pieceType) {
  // 检查行
  let rowWin = true;
  for (let k = 0; k < gameState.cols; k++) {
    if (gameState.board[i][k] !== pieceType) {
      rowWin = false;
      break;
    }
  }
  if (rowWin) return true;

  // 检查列
  let colWin = true;
  for (let k = 0; k < gameState.rows; k++) {
    if (gameState.board[k][j] !== pieceType) {
      colWin = false;
      break;
    }
  }
  if (colWin) return true;

  // 检查对角线 (从左上到右下)
  if (i === j) {
    let diagWin = true;
    for (let k = 0; k < gameState.rows; k++) {
      if (gameState.board[k][k] !== pieceType) {
        diagWin = false;
        break;
      }
    }
    if (diagWin) return true;
  }

  // 检查对角线 (从右上到左下)
  if (i + j === gameState.rows - 1) {
    let diagWin = true;
    for (let k = 0; k < gameState.rows; k++) {
      if (gameState.board[k][gameState.rows - 1 - k] !== pieceType) {
        diagWin = false;
        break;
      }
    }
    if (diagWin) return true;
  }

  return false;
}

/**
 * 检查是否平局
 */
function checkTie() {
  for (let i = 0; i < gameState.rows; i++) {
    for (let j = 0; j < gameState.cols; j++) {
      if (gameState.board[i][j] === null) {
        return false; // 还有空位，不是平局
      }
    }
  }
  return true; // 棋盘已满，平局
}

/**
 * 重新开始游戏
 */
function restartGame() {
  initBoard();
}

/**
 * 切换准备状态
 */
function toggleReadyStatus() {
  isReady.value = !isReady.value;
  gameTip.value = isReady.value ? '已准备' : '未准备';
  // 这里应该发送WebSocket消息通知其他玩家
}

/**
 * 返回游戏大厅
 */
function backToLobby() {
  // 导航回游戏空间
  router.push('/pages/games/index');
}

// 生命周期钩子
onMounted(() => {
  // 获取用户信息和房间ID (实际应用中应该从登录状态或URL参数获取)
  // 这里只是示例，实际项目中需要替换为真实的获取方式
  userId.value = 'user123';
  userName.value = '玩家1';
  roomId.value = 'room012';

  // 初始化玩家列表
  players.value = [
    { user_id: userId.value, user_name: userName.value, ready: false },
    { user_id: 'user345', user_name: '等待加入...', ready: false }
  ];

  // 初始化棋盘
  initBoard();
});
</script>

<style scoped>
.tictactoe-game-container {
  padding: 16px;
  min-height: 100vh;
  background: linear-gradient(135deg, #e0e7ff 0%, #f8fafc 100%);
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #6366f1;
}

.user-info {
  font-size: 14px;
  color: #1f2937;
}

.game-status {
  font-size: 14px;
  font-weight: bold;
  color: #6366f1;
}

.game-tip {
  font-size: 14px;
  color: #6b7280;
}

.game-area {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 32px rgba(99, 102, 241, 0.2);
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.game-title {
  font-size: 18px;
  font-weight: bold;
  color: #4f46e5;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.game-title i {
  margin-right: 8px;
}

.player-list {
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 320px;
  margin-bottom: 16px;
  gap: 10px;
}

.player-card {
  flex: 1;
  background: #f3f4f6;
  border-radius: 10px;
  padding: 10px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.player-card.current {
  border: 2px solid #6366f1;
  background: #f0f4ff;
}

.piece-type {
  margin-top: 4px;
  font-size: 16px;
}

.game-board {
  margin: 20px 0;
  background: #ffffff;
  border-radius: 12px;
  padding: 10px;
  box-shadow: 0 2px 12px rgba(99, 102, 241, 0.1);
}

.board-row {
  display: flex;
}

.board-cell {
  width: 80px;
  height: 80px;
  border: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.board-cell:hover {
  background: #f3f4f6;
}

.cell-content {
  font-size: 32px;
  font-weight: bold;
}

.cell-content.X {
  color: #ef4444;
}

.cell-content.O {
  color: #3b82f6;
}

.control-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: center;
}

.restart-btn, .ready-btn, .back-btn {
  padding: 8px 16px;
  border-radius: 50px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
}

.restart-btn {
  background: linear-gradient(90deg, #6366f1 0%, #818cf8 100%);
  color: white;
}

.ready-btn {
  background: #f3f4f6;
  color: #1f2937;
}

.back-btn {
  background: #fee2e2;
  color: #dc2626;
}

.restart-btn:hover {
  opacity: 0.9;
  transform: scale(1.05);
}
</style>